<?php

function get_val_int(&$_array, $_name, $_define)
{
	return array_key_exists($_name, $_array) ? intval($_array[$_name]) : $_define;
}

function get_val($_array, $_name, $_define)
{
	return array_key_exists($_name, $_array) ? $_array[$_name] : $_define;
}

header("Content-type: text/html; charset=utf-8");

$page =  get_val_int($_GET, 'page', 1);
$limit = get_val_int($_GET, 'rows', 0);
$sidx = get_val($_GET, 'sidx', '');
$sord = get_val($_GET, 'sord', '');

$admin = true;

require_once('auth_req.inc.php');

$rs = $dbh->query('select count(*) from network_map');

if ($rec = $rs->fetchAll(PDO::FETCH_COLUMN, 0))
{
    $count = $rec[0];
}
else
{
    $count = 0;
}

if( $count > 0 ) 
{ 
    $total_pages = ceil($count/$limit); 
} 
else 
{ 
    $total_pages = 0; 
} 

if ($page > $total_pages) 
    $page=$total_pages;


$start = $limit * $page - $limit;

if ($start < 0) 
    $start = 0;

$order_by_cause = 'order by ';

$idx_array = array('c_id' => 'nm.c_id', 'g_name' => 'gr.name', 'c_location' => 'nm.location');

$idx = $idx_array[$sidx];

if (isset($idx) && (($sord == 'asc') || ($sord == 'desc')))
{                     
    $order_by_cause .= $idx . ' ' . $sord;
}
else
{
    $order_by_cause = '';
}


$sth = $dbh->prepare('SELECT nm.c_id, gr.name as g_name, nm.location, nm.next_enc_key ' .  
                     'FROM network_map nm, groups gr ' .  
                     'WHERE gr.g_id = nm.g_id ' . $order_by_cause . ' limit :start,:limit');

$sth->bindParam(':start', $start, PDO::PARAM_INT);
$sth->bindParam(':limit', $limit, PDO::PARAM_INT);

$sth->execute();

$response = new stdClass();

$response->page = $page; 
$response->total = $total_pages; 
$response->records = $count; 

$alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

foreach( $alldb as $key => $val)
{
    $response->rows[$key]['id'] = $val['c_id'];
    $response->rows[$key]['cell'] = array( $val['c_id'], $val['g_name'],$val['location'],$val['next_enc_key']);
}

echo json_encode($response);

?>
